export default class ResPreloader {

    isInitedList = false;
    private resPathList: { [key: string]: typeof cc.Asset } = {};
    private resList: { [key: string]: any } = {};
    private totalCount: number = 0;
    private loadedCount: number = 0;

    /** 添加资源进列表，准备预加载 */
    addRes(path: string, type: typeof cc.Asset) {
        if (!this.resPathList.hasOwnProperty(path)) {
            this.resPathList[path] = type;
            this.totalCount = Object.keys(this.resPathList).length;
        }
    }

    /** 开始批量下载资源,加载完成一次后再次调用不会重复下载，直接返回进度1 */
    load(onProgress: Function, onError?: Function) {
        this.isInitedList = true;
        if (this.loadedCount == this.totalCount) {
            if (onProgress) {
                onProgress(1);
            }
            return;
        }
        if (onProgress) {
            onProgress(0);
        }
        if (this.totalCount == 0) {
            if (onProgress) {
                onProgress(1);
            }
            return;
        }
        for (let key in this.resPathList) {
            let type: typeof cc.Asset = this.resPathList[key];
            cc.loader.loadRes(key, type, (err, asset) => {
                if (err) {
                    console.error(err);
                    console.error('[path: ' + key + ']');
                    if (onError) {
                        onError();
                    }
                    return;
                }
                this.resList[key] = asset;
                this.loadedCount += 1;
                if (onProgress) {
                    onProgress(this.loadedCount / this.totalCount);
                }
            })
        }
    }

    /** 获取下载好的资源 */
    getRes(path: string): any {
        let asset = this.resList[path];
        if (!asset) {
            console.error('资源未添加到预加载列表或预加载失败：' + path);
        }
        return asset;
    }

}
